package com.cyberEye.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.team2.shared.CyberException;
import com.team2.shared.SharedConstants;
import com.team2.shoppingService.Configuration;
import com.team2.shoppingService.Shopper;
import com.team2.shoppingService.Util;

public class BarcodeServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -964695137291296816L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		//set up path prefix
		String prefix = getServletContext().getRealPath("/WEB-INF/WebParserConfigFiles")+"/";
		System.out.println(prefix);
		Configuration.setPathPrefix(prefix);
	
		System.out.println("Getting Barcode Request!");
		resp.setContentType("text/plain");
		String barcode = req.getParameter(SharedConstants.BARCODE);
		String token = req.getParameter("token");
		if(token ==null || !token.equals(Util.computeHashFromBytes(SharedConstants.TOKEN.getBytes()))){
			resp.setStatus(999);
			resp.getWriter().println("Unauthorized Access! Token is missing");
			System.out.println("Getting Barcode Request!,Unauthorized Access! Token is missing");
			return;
		}
		if(barcode==null || barcode.isEmpty()){
			resp.setStatus(666);
			resp.getWriter().println("Parameter [barcode] is required!");
			System.out.println("Getting Barcode Request!,Missing Parameter");
			return;
		}
		System.out.println(barcode);
		try {
			String result = Shopper.searchFromBarcode(barcode);
			resp.getWriter().println(result);
			System.out.println("Reply to Barcode Request,"+result);
		} catch (CyberException e) {
			resp.setStatus(777);
			resp.getWriter().println(e.getMessage());
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}

}
